package com.doit.demo.day02.transformations;

import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.typeinfo.TypeHint;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.operators.AbstractStreamOperator;
import org.apache.flink.streaming.api.operators.OneInputStreamOperator;
import org.apache.flink.streaming.api.operators.StreamMap;
import org.apache.flink.streaming.runtime.streamrecord.StreamRecord;

/**
 * @DATE 2022/2/27/11:55
 * @Author MDK
 * @Version 2021.2.2
 *
 *
 * map方法底层调用的是transform方法,输入三个参数
 *      第一个:算子名称
 *      第二个:返回的数据类型
 *      第一个:调用的函数(数据处理的实现类)
 *
 * 不直接调用map方法,而是调用transform方法实现与map一样的功能!!
 *      StreamMap类底层的具体实现
 *
 *      Flink底层有一个processElement方法,每输入一条数据就会调用一次该方法,输出数据用output对象输出
 *
 **/
public class MapDemo5 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        DataStreamSource<String> lines = env.socketTextStream("linux01", 8888);

        /*MapFunction<String, String> mapFunction = new MapFunction<String, String>() {
            @Override
            public String map(String value) throws Exception {
                return value.toUpperCase();
            }
        };*/

        SingleOutputStreamOperator<Tuple2<String, Integer>> res = lines.transform(
                "MyMap",
                TypeInformation.of(new TypeHint<Tuple2<String, Integer>>(){}),
                new MyMap());

        res.print();

        env.execute();

    }

    private static class MyMap extends AbstractStreamOperator<Tuple2<String, Integer>> implements OneInputStreamOperator<String, Tuple2<String, Integer>>{
        @Override
        public void processElement(StreamRecord<String> element) throws Exception {
            String lines = element.getValue();
            String[] fields = lines.split(",");
            String word = fields[0];
            int count = Integer.parseInt(fields[1]);
            output.collect(element.replace(Tuple2.of(word, count)));
        }
    }
}
